package io.sundial.discovery.impl;

import io.sundial.core.context.Context;
import io.sundial.core.event.Event;
import io.sundial.core.event.EventListener;
import io.sundial.core.event.EventSource;
import io.sundial.core.event.EventSourceSupplier;
import io.sundial.core.lifecycle.Stateful;
import io.sundial.core.lifecycle.exception.DestroyingException;
import io.sundial.core.lifecycle.exception.InitializingException;
import io.sundial.discovery.Discoverer;
import io.sundial.discovery.DiscovererEvent;

/**
 * 事件支持的作业发现者
 *
 * @author Payne 646742615@qq.com
 * 2019/1/4 17:59
 */
public abstract class EventSupportingDiscoverer extends Stateful implements Discoverer {
    private EventSource eventSource;

    protected void fire(Event event) {
        eventSource.fire(event);
    }

    protected void shut() {
        eventSource.shut();
    }

    @Override
    protected void initializing(Context context) throws InitializingException {
        super.initializing(context);

        //region 绑定事件源
        eventSource = eventSource != null
                ? eventSource
                : context.get(EventSource.class, new EventSourceSupplier());
        //endregion
    }

    @Override
    protected void destroying() throws DestroyingException {
        super.destroying();

        eventSource = null;
    }

    @Override
    public void addEventListener(EventListener<? extends DiscovererEvent> listener) {
        eventSource.addEventListener(listener);
    }

    @Override
    public void removeEventListener(EventListener<? extends DiscovererEvent> listener) {
        eventSource.removeEventListener(listener);
    }

    public EventSource getEventSource() {
        return eventSource;
    }

    public void setEventSource(EventSource eventSource) {
        this.eventSource = eventSource;
    }
}
